import 'dart:async';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:just_audio/just_audio.dart';
import 'package:provider/provider.dart';
import 'package:tencent_cloud_chat_uikit/business_logic/separate_models/tui_chat_separate_view_model.dart';
import 'package:tencent_cloud_chat_uikit/business_logic/view_models/tui_chat_global_model.dart';
import 'package:xindong/common/xindong_sezhi.dart';
import 'package:xindong/manager/xindong_chat_singleton.dart';
import 'package:xindong/routes/conversation/view/xindong_liaotian_message_score_container.dart';
import 'package:tencent_cloud_chat_uikit/data_services/message/message_services.dart';
import 'package:tencent_cloud_chat_uikit/data_services/services_locatar.dart';
import 'package:tencent_cloud_chat_uikit/tencent_cloud_chat_uikit.dart';
import 'package:tencent_cloud_chat_uikit/ui/constants/history_message_constant.dart';
import 'package:tencent_cloud_chat_uikit/ui/utils/platform.dart';
import 'package:tencent_cloud_chat_uikit/ui/utils/sound_record.dart';

class XinDongLiaoTianMessageSound extends StatefulWidget {
  final V2TimMessage message;
  final double maxWidth;
  final Function() clearJump;

  const XinDongLiaoTianMessageSound(
      {Key? key, required this.message, required this.maxWidth, required this.clearJump})
      : super(key: key);

  @override
  State<XinDongLiaoTianMessageSound> createState() => _XinDongLiaoTianMessageSoundState();
}

class _XinDongLiaoTianMessageSoundState extends State<XinDongLiaoTianMessageSound> {
  late final TUIChatSeparateViewModel chatVM;
  final int charLen = 8;
  bool isPlaying = false;
  StreamSubscription<Object>? subscription;
  bool isShining = false;
  final TUIChatGlobalModel globalClass = serviceLocator<TUIChatGlobalModel>();
  final MessageService _messageService = serviceLocator<MessageService>();
  late V2TimSoundElem stateElement = widget.message.soundElem!;

  _playSound() async {
    if (!SoundPlayer.isInit) {
      SoundPlayer.initSoundPlayer();
    }
    if (widget.message.localCustomInt == null || widget.message.localCustomInt != HistoryMessageDartConstant.read) {
      globalClass.setLocalCustomInt(
          widget.message.msgID ?? "", HistoryMessageDartConstant.read, chatVM.conversationID);
    }
    if (isPlaying) {
      SoundPlayer.stop();
      chatVM.currentPlayedMsgId = "";
    } else {
      SoundPlayer.play(url: stateElement.url!);
      chatVM.currentPlayedMsgId = widget.message.msgID ?? "";
      // SoundPlayer.setSoundInterruptListener(() {
      //   // setState(() {
      //   isPlaying = false;
      //   // });
      // });
    }
  }

  downloadMessageDetailAndSave() async {
    if (widget.message.msgID != null && widget.message.msgID != '') {
      if (widget.message.soundElem!.url == null || widget.message.soundElem!.url == '') {
        final response = await _messageService.getMessageOnlineUrl(msgID: widget.message.msgID!);
        widget.message.soundElem = response.data!.soundElem;
        Future.delayed(const Duration(microseconds: 10), () {
          setState(() => stateElement = response.data!.soundElem!);
        });
      }
      if (!PlatformUtils().isWeb) {
        if (widget.message.soundElem!.localUrl == null || widget.message.soundElem!.localUrl == '') {
          _messageService.downloadMessage(
              msgID: widget.message.msgID!, messageType: 4, imageType: 0, isSnapshot: false);
        }
      }
    }
  }

  @override
  void didUpdateWidget(oldWidget) {
    super.didUpdateWidget(oldWidget);
    setState(() {
      isPlaying = chatVM.currentPlayedMsgId != '' && chatVM.currentPlayedMsgId == widget.message.msgID;
    });
  }

  @override
  void initState() {
    super.initState();
    chatVM = Provider.of<TUIChatSeparateViewModel>(context, listen: false);

    subscription = SoundPlayer.playStateListener(listener: (PlayerState state) {
      if (state.processingState == ProcessingState.completed) {
        chatVM.currentPlayedMsgId = "";
        // SoundPlayer.removeSoundInterruptListener();
      }
    });
    downloadMessageDetailAndSave();
  }

  @override
  void dispose() {
    if (isPlaying) {
      SoundPlayer.stop();
      chatVM.currentPlayedMsgId = "";
    }
    subscription?.cancel();
    super.dispose();
  }

  double _getSoundLen() {
    double soundLen = 32;
    if (stateElement.duration != null) {
      final realSoundLen = stateElement.duration!;
      int sdLen = 32;
      if (realSoundLen > 10) {
        sdLen = 12 * charLen + ((realSoundLen - 10) * charLen / 0.5).floor();
      } else if (realSoundLen > 2) {
        sdLen = 2 * charLen + realSoundLen * charLen;
      }
      sdLen = min(sdLen, 20 * charLen);
      soundLen = sdLen.toDouble();
    }

    return soundLen;
  }

  @override
  Widget build(BuildContext context) {
    final isFromSelf = widget.message.isSelf == true;
    final backgroundColor = isFromSelf ? Colors.grey.shade300 : Colors.white;

    return InkWell(
      onTap: () => _playSound(),
      child: GetBuilder<XinDongChatSingleton>(
        builder: (controller) {
          return XinDongLiaoTianMessageScoreContainer(
            hidden: isFromSelf,
            message: widget.message,
            child: Container(
              padding: const EdgeInsets.all(10),
              decoration: BoxDecoration(color: backgroundColor, borderRadius: BorderRadius.circular(10)),
              constraints: BoxConstraints(maxWidth: widget.maxWidth),
              child: sound(isFromSelf),
            ),
          );
        },
      ),
    );
  }

  Widget sound(isFromSelf) {
    const TextStyle textStyle = TextStyle(fontSize: 16, height: 1.2, color: DZColors.titleColor);
    return Column(
      children: [
        Row(
          mainAxisSize: MainAxisSize.min,
          children: isFromSelf
              ? [
                  Container(width: _getSoundLen()),
                  Text("''${stateElement.duration} ", style: textStyle),
                  isPlaying
                      ? Image.asset(
                          'images/play_voice_send.gif',
                          package: 'tencent_cloud_chat_uikit',
                          width: 16,
                          height: 16,
                        )
                      : Image.asset(
                          'images/voice_send.png',
                          package: 'tencent_cloud_chat_uikit',
                          width: 16,
                          height: 16,
                        ),
                ]
              : [
                  isPlaying
                      ? Image.asset(
                          'images/play_voice_receive.gif',
                          package: 'tencent_cloud_chat_uikit',
                          width: 16,
                          height: 16,
                        )
                      : Image.asset(
                          'images/voice_receive.png',
                          width: 16,
                          height: 16,
                          package: 'tencent_cloud_chat_uikit',
                        ),
                  Text(" ${stateElement.duration}''", style: textStyle),
                  Container(width: _getSoundLen()),
                ],
        ),
      ],
    );
  }
}
